<template>
  <div class="cos-test">
    <h2>COS服务测试</h2>
    
    <div class="test-section">
      <h3>配置信息</h3>
      <div class="config-info">
        <div class="config-item">
          <strong>匿名模式:</strong> {{ config.useAnonymous ? '是' : '否' }}
        </div>
        <div class="config-item">
          <strong>存储桶:</strong> {{ config.Bucket }}
        </div>
        <div class="config-item">
          <strong>地区:</strong> {{ config.Region }}
        </div>
        <div class="config-item">
          <strong>路径前缀:</strong> {{ config.Prefix }}
        </div>
        <div class="config-item">
          <strong>域名:</strong> {{ config.Domain }}
        </div>
        <div class="config-item">
          <strong>CDN域名:</strong> {{ config.cdnDomain }}
        </div>
        <div class="config-item">
          <strong>服务状态:</strong> {{ isInitialized ? '已初始化' : '未初始化' }}
        </div>
      </div>
      
      <el-divider />
      
      <div class="test-actions">
        <el-button type="primary" @click="initService" :loading="loading">
          初始化COS服务
        </el-button>
        
        <el-button type="success" @click="testListFiles" :disabled="!isInitialized" :loading="loading">
          测试列出文件
        </el-button>
        
        <el-button type="warning" @click="testWithSdk" :loading="loading">
          直接用SDK测试
        </el-button>
        
        <el-input 
          v-model="testPath" 
          placeholder="测试路径，例如: docs/" 
          class="test-input"
        />
      </div>
    </div>
    
    <div class="response-section">
      <h3>测试结果</h3>
      
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="error" class="error-state">
        <h4>错误信息:</h4>
        <pre class="error-message">{{ error }}</pre>
      </div>
      
      <div v-else-if="result" class="result-state">
        <h4>目录: {{ currentPath || '根目录' }}</h4>
        
        <div class="result-summary">
          <div class="summary-item">
            <strong>文件夹数量:</strong> {{ result.directories?.length || 0 }}
          </div>
          <div class="summary-item">
            <strong>文件数量:</strong> {{ result.files?.length || 0 }}
          </div>
          <div class="summary-item">
            <strong>完整前缀:</strong> {{ result.prefix }}
          </div>
        </div>
        
        <el-tabs type="border-card">
          <el-tab-pane label="文件夹">
            <el-table :data="result.directories" border stripe>
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="prefix" label="前缀" />
            </el-table>
            <div v-if="!result.directories?.length" class="empty-notice">
              无文件夹
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="文件">
            <el-table :data="result.files" border stripe>
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="type" label="类型" />
              <el-table-column prop="size" label="大小" />
              <el-table-column prop="url" label="URL">
                <template #default="scope">
                  <el-link type="primary" :href="scope.row.url" target="_blank">
                    {{ scope.row.url.substring(0, 50) }}{{ scope.row.url.length > 50 ? '...' : '' }}
                  </el-link>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="!result.files?.length" class="empty-notice">
              无文件
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="原始数据">
            <pre class="raw-data">{{ JSON.stringify(result, null, 2) }}</pre>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <div v-else class="no-result">
        <el-empty description="尚未运行测试" />
      </div>
    </div>
    
    <!-- SDK测试结果 -->
    <div v-if="sdkTestResult" class="result-section">
      <h3>SDK测试结果</h3>
      <pre class="raw-data">{{ JSON.stringify(sdkTestResult, null, 2) }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import cosFileService from '../../services/CosFileService';
import COS from 'cos-js-sdk-v5';

// 状态管理
const loading = ref(false);
const error = ref(null);
const result = ref(null);
const isInitialized = ref(false);
const testPath = ref('');
const currentPath = ref('');
const sdkTestResult = ref(null);

// COS配置
const config = reactive({
  useAnonymous: false, // 使用永久密钥模式
  SecretId: 'AKIDUuMlw1veATYYKuMciaGj6IJ8jIvOfmur',
  SecretKey: 'oPn26xdCaljfT82kIdlgOvkXBfw0wzue',
  Bucket: 'mybox-1257251314',
  Region: 'ap-chengdu',
  Prefix: 'www/educoder/file/',
  Domain: 'https://mybox-1257251314.cos.ap-chengdu.myqcloud.com',
  cdnDomain: 'https://cos.roginx.ink'
});

// 初始化COS服务
const initService = async () => {
  loading.value = true;
  error.value = null;
  result.value = null;
  
  try {
    const initialized = cosFileService.init(config);
    
    if (initialized) {
      isInitialized.value = true;
      ElMessage.success('COS服务初始化成功');
    } else {
      ElMessage.error('COS服务初始化失败');
    }
  } catch (e) {
    console.error('初始化失败:', e);
    error.value = e.message || '初始化COS服务时发生未知错误';
    ElMessage.error('初始化COS服务失败');
  } finally {
    loading.value = false;
  }
};

// 测试列出文件
const testListFiles = async () => {
  if (!isInitialized.value) {
    ElMessage.warning('请先初始化COS服务');
    return;
  }
  
  loading.value = true;
  error.value = null;
  result.value = null;
  
  try {
    currentPath.value = testPath.value;
    const response = await cosFileService.listFiles(testPath.value);
    result.value = response;
    
    ElMessage.success(`成功获取文件列表: 文件夹(${response.directories?.length || 0})，文件(${response.files?.length || 0})`);
  } catch (e) {
    console.error('列出文件失败:', e);
    error.value = e.message || '列出文件时发生未知错误';
    ElMessage.error('列出文件失败');
  } finally {
    loading.value = false;
  }
};

// 直接使用COS SDK测试
const testWithSdk = async () => {
  loading.value = true;
  error.value = null;
  sdkTestResult.value = null;
  
  try {
    console.log('使用原生SDK测试COS连接');
    
    // 创建COS实例
    const cos = new COS({
      SecretId: config.SecretId,
      SecretKey: config.SecretKey,
      // 不再使用匿名模式
    });
    
    // 构建完整前缀
    const fullPrefix = testPath.value ? 
      (config.Prefix + (testPath.value.startsWith('/') ? testPath.value.substring(1) : testPath.value)) : 
      config.Prefix;
      
    console.log('测试路径:', fullPrefix);
    
    // 使用SDK直接列出文件
    const result = await new Promise((resolve, reject) => {
      cos.getBucket({
        Bucket: config.Bucket,
        Region: config.Region,
        Prefix: fullPrefix,
        Delimiter: '/'
      }, (err, data) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(data);
      });
    });
    
    // 显示结果
    sdkTestResult.value = result;
    console.log('SDK测试结果:', result);
    ElMessage.success('SDK测试成功');
  } catch (e) {
    console.error('SDK测试失败:', e);
    error.value = `SDK测试失败: ${e.message || JSON.stringify(e)}`;
    ElMessage.error('SDK测试失败');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时自动初始化
onMounted(() => {
  // 不自动初始化以避免可能的错误
});
</script>

<style scoped>
.cos-test {
  padding: 20px;
}

.test-section, .response-section {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.config-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.config-item {
  padding: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.test-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.test-input {
  width: 300px;
}

.error-message {
  background-color: #fff1f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  padding: 10px;
  color: #cf1322;
  overflow-x: auto;
}

.result-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.summary-item {
  padding: 10px;
  border-radius: 4px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.raw-data {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 10px;
  overflow-x: auto;
  font-size: 14px;
}

.empty-notice {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.loading-state, .error-state, .result-state, .no-result {
  margin-top: 20px;
}

h2, h3, h4 {
  margin-bottom: 16px;
}
</style> 